package com.ks.app.search.action;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import com.ks.app.admin.action.BaseAction;
import com.ks.app.search.util.RequestUtil;

@ParentPackage("struts-default")
@InterceptorRef("defaultStack")
@Results( {
	@Result(name = "search",    location = "/WEB-INF/search/result.jsp"),         //网页搜索结果
	@Result(name = "news",      location = "/WEB-INF/search/news.jsp"),             //新闻搜索结果
	@Result(name = "picture",   location = "/WEB-INF/search/picture.jsp"),           //图片搜索结果
	@Result(name = "know",      location = "/WEB-INF/search/know.jsp"),             //知道搜索结果
	
	@Result(name = "aboutkso", location = "/WEB-INF/search/aboutkso.jsp"),     //关于酷搜沃
	@Result(name = "coopekso", location = "/WEB-INF/search/coopekso.jsp")      //合作
})
public class KsSearchAction extends BaseAction{

	private static final long serialVersionUID = 7406354228119551353L;
	private Log log = LogFactory.getLog(this.getClass());
	
	SimpleDateFormat df=new SimpleDateFormat("HH:mm MM-dd"); 
	private String now=df.format(new Date());
	
	private static String nextpage="",prepage="";
	
	public  static String pram="";
	
	public  static String getPram() {
		return pram;
	}

	public static void setPram(String pram) {
		KsSearchAction.pram = pram;
	}

		
	/**
	 * 搜索接口
	 * @return
	 */
	@Action(value="ksosearch")
	public String ksoSearch(){
			
		   //st 搜索类型  1：网页，2：图片，3：新闻，4：地图
           //           5：知道，6：百科，7：MP3，8：视频
           //           9：应用，10：贴吧，11：小说，12：天气

			     		            
		   int searchType = request.getParameter("sty")==null?1:Integer.parseInt(request.getParameter("sty"));
		   
		   switch(searchType){
			
		    //网页搜索
			case 1:      
						 return websiteSearch();
			//图片搜索			 
            case 2:      
		                 return pictureSearch();		             
		    //新闻搜索
			case 3:      
						 return newsSearch();
			//地图搜索
			case 4:
						 return mapSearch();
			//知道搜索
			case 5:
						 return knowSearch();
			/*//百科搜索			
			case 6:
				         return baikeSearch();
			//mp3搜索
			case 7:
				         return mp3Search();
			//视频搜索
			case 8:
						 return vedioSearch();*/
			//默认为网页搜索   
			default:             
					return websiteSearch();
		}
		   
	}
	
	/**
	 * 网页搜索
	 * @return
	 */
	public String websiteSearch(){
		
		// f:第一页，n：下一页，p：上一页
		   String pno       = request.getParameter("pno")==null?"f":request.getParameter("pno").toString().trim();    
		   // 搜索关键字
		   String keyword	= request.getParameter("keyword")==null?"":request.getParameter("keyword").toString().trim();
		   
		   String kutf8  = ""; 
		   String result = "";
		   
		   if("f".equals(pno)){
			   
			   String ver	= request.getParameter("ver")==null?"":request.getParameter("ver").toString().trim();	
			   String src	= request.getParameter("src")==null?"":request.getParameter("src").toString().trim();	
			   String plat	= request.getParameter("plat")==null?"":request.getParameter("plat").toString().trim();	
			   String imsi	= request.getParameter("imsi")==null?"":request.getParameter("imsi").toString().trim();	
			   String clnt	= request.getParameter("clnt")==null?"":request.getParameter("clnt").toString().trim();	
			   String smsc	= request.getParameter("smsc")==null?"":request.getParameter("smsc").toString().trim();		   
			   pram="ver="+ver+"&amp;src="+src+"&amp;plat="+plat+"&amp;imsi="+imsi+"&amp;clnt="+clnt+"&amp;smsc="+smsc;
			
		   }
			   
		   request.setAttribute("pram", pram);		
		   
		   try {
			    keyword = new String(keyword.getBytes("ISO8859-1"),"utf-8");
		    	kutf8 = URLEncoder.encode(keyword,"utf-8");
		   } catch (Exception e) {
			    log.info(kutf8+""+e.getMessage());
				e.printStackTrace();
		   }
		    
		   if(keyword.trim().length()>0)
		   {	
				keyword=keyword.replace(" ","");
				request.setAttribute("keyword",keyword);
				
				if("f".equals(pno)){
					String url = "http://m.baidu.com/s?from=1292a&st=102041&word="+keyword;
					result = RequestUtil.sendConnRequest(url);
				}else if("n".equals(pno)){
					result = RequestUtil.sendConnRequest(nextpage.replace("&amp;","&"));
				}else if("p".equals(pno)){
					result = RequestUtil.sendConnRequest(prepage.replace("&amp;","&"));
				}
				
				
				if(result.indexOf("<div class=\"reswrap\">抱歉")>-1){
					
		    		result="抱歉,没有找到\""+keyword+"\"的相关内容.<br/>";
		    		request.setAttribute("result", result);
		    		
		    	}else{
		    		
					String styles=result.substring(result.indexOf("<style"),result.indexOf("</style")+8);
					if(result.indexOf("<div class=\"bc relate\">相关搜索:")>-1)
					{
						result=result.substring(result.indexOf("</form>")+7,result.lastIndexOf("<div class=\"bc relate\">相关搜索:"));
					}
					else{
					    result=result.substring(result.indexOf("</form>")+7,result.lastIndexOf("<form"));
					}
					result=result.replaceAll("</div<", "</div></div><");
					result=result.replaceAll("<a href=\"/","<a href=\"http://m.baidu.com/");
					
					String ol="href='/";
					result=result.replaceAll(ol,"href='http://m.baidu.com/");
					result=result.replaceAll("</div></div>", "</div></div><br/>");
					if(result.indexOf("<div class=\"pagenav\"")>-1)
					{
						String appendnext="",appendpre="";
						if(result.indexOf("下一页</a>")>0)
						{
							String nextpagehref=result.substring(result.indexOf("<div class=\"pagenav\" >"),result.indexOf("下一页</a>"));
							nextpage=nextpagehref.substring(31, nextpagehref.length()-2).replace("./s?","http://m.baidu.com/from=1292a/bd_page_type=1/ssid=0/uid=wiaui_1316749067_3686/pu=usm%400%2Csz%40224_220/s?");
							appendnext="<a href=\"ksosearch?sty=1&pno=n&keyword="+kutf8+"\">下一页</a>";
						}
						if(result.indexOf("上一页</a>")>0)
						{							
							if(result.indexOf("下一页</a>&#160;&#160;")>0)
							{
								String prepagehref=result.substring(result.indexOf("下一页</a>&#160;&#160;"),result.indexOf("上一页</a>"));
								prepage=prepagehref.substring(28, prepagehref.length()-2).replace("./s?","http://m.baidu.com/from=1292a/bd_page_type=1/ssid=0/uid=wiaui_1316749067_3686/pu=usm%400%2Csz%40224_220/s?");
								appendpre="<a href=\"ksosearch?sty=1&pno=p&keyword="+kutf8+"\">上一页</a>";
							}
							else
							{
								String prepagehref=result.substring(result.indexOf("<div class=\"pagenav\" >"),result.indexOf("上一页</a>"));
								prepage=prepagehref.substring(31, prepagehref.length()-2).replace("./s?","http://m.baidu.com/from=1292a/bd_page_type=1/ssid=0/uid=wiaui_1316749067_3686/pu=usm%400%2Csz%40224_220/s?");
								appendpre="<a href=\"ksosearch?sty=1&pno=p&keyword="+kutf8+"\">上一页</a>";
							}
						}				
						result=result.substring(0,result.indexOf("<div class=\"pagenav\" >"))+appendnext.trim()+"  "+appendpre.trim()+"<br/>";
					}
					result=result.replaceAll("<a href=\"./s?","<a href=\"http://m.baidu.com/from=1292a/bd_page_type=1/ssid=0/uid=wiaui_1316749067_3686/pu=usm%400%2Csz%40224_220/t=wap/l=1/tc?");				
					request.setAttribute("result", result);
					request.setAttribute("styles", styles);
		    	}		
		}
		else
		{
			request.setAttribute("result", "请输入关键字！<br/><br/>");
		}
		   
		request.setAttribute("now", now);
		return "search";
	}
	
	/**
	 * 新闻搜索
	 * @return
	 */
	public String newsSearch(){
		
		   // f:第一页，n：下一页，p：上一页
		   String pno       = request.getParameter("pno")==null?"f":request.getParameter("pno").toString().trim();    
		   // 搜索关键字
		   String keyword	= request.getParameter("keyword")==null?"":request.getParameter("keyword").toString().trim();
		   
		   String kutf8  = ""; 
		   String result = "";
		   
		   if("f".equals(pno)){
			   
			   String ver	= request.getParameter("ver")==null?"":request.getParameter("ver").toString().trim();	
			   String src	= request.getParameter("src")==null?"":request.getParameter("src").toString().trim();	
			   String plat	= request.getParameter("plat")==null?"":request.getParameter("plat").toString().trim();	
			   String imsi	= request.getParameter("imsi")==null?"":request.getParameter("imsi").toString().trim();	
			   String clnt	= request.getParameter("clnt")==null?"":request.getParameter("clnt").toString().trim();	
			   String smsc	= request.getParameter("smsc")==null?"":request.getParameter("smsc").toString().trim();		   
			   pram="ver="+ver+"&amp;src="+src+"&amp;plat="+plat+"&amp;imsi="+imsi+"&amp;clnt="+clnt+"&amp;smsc="+smsc;
			
		   }		  
		   
		   request.setAttribute("pram", pram);		
		   
		   try {
			    keyword = new String(keyword.getBytes("ISO8859-1"),"utf-8");
		    	kutf8 = URLEncoder.encode(keyword,"utf-8");
		   } catch (Exception e) {
			    log.info(kutf8+""+e.getMessage());
				e.printStackTrace();
		   }
		    
		   if(keyword.trim().length()>0)
		   {	
				keyword=keyword.replace(" ","");
				request.setAttribute("keyword",keyword);
				
				if("f".equals(pno)){
					String url = "http://baidu.mobi/news?from=1292a&st=102041&word="+keyword;
					result = RequestUtil.sendConnRequest(url);
				}else if("n".equals(pno)){
					result = RequestUtil.sendConnRequest(nextpage.replace("&amp;","&"));
				}else if("p".equals(pno)){
					result = RequestUtil.sendConnRequest(prepage.replace("&amp;","&"));
				}
				
				
				if(result.indexOf("<div class=\"reswrap\">抱歉")>-1){
					
		    		result="抱歉,没有找到\""+keyword+"\"的相关内容.<br/>";
		    		request.setAttribute("result", result);
		    		
		    	}else{
		    		
		    		String styles = result.substring(result.indexOf("<style"),result.indexOf("</style")+8);
					if(result.indexOf("重新搜索")<0){
						result="暂无"+keyword+"相关结果,请重新搜索!";
						request.setAttribute("result", result);
						request.setAttribute("styles", styles);
						request.setAttribute("now", now);				
						return "news";
					}
					
					result=result.substring(result.indexOf("重新搜索")+20,result.lastIndexOf("回顶部")-30);
			      	if(result.indexOf("<a href=\"news?")>-1){
						result=result.replaceAll("<a href=\"news?","<a href=\"http://m.baidu.com/ssid=0/from=1292a/bd_page_type=1/news?");			
					}
					if(result.indexOf("<a href=\"t=news/tc")>-1){
						result=result.replaceAll("<a href=\"t=news/tc","<a href=\"http://m.baidu.com/ssid=0/from=1292a/bd_page_type=1/t=news/tc");
					}
					result=result.replaceAll("<a href=\"./","<a href=\"http://m.baidu.com/");
					result=result.replaceAll("</div>","</div><br/>");   
					 
					if(result.indexOf("<div class=\"d\"")>-1)
					{
						String appendnext="",appendpre="";
						if(result.indexOf("下一页</a>")>0)
						{
							String nextpagehref=result.substring(result.indexOf("<div class=\"d\">"),result.indexOf("下一页</a>"));
							nextpage=nextpagehref.substring(24, nextpagehref.length()-2);
							appendnext="<a href=\"ksosearch?sty=3&pno=n&keyword="+kutf8+"\">下一页</a>";
						}					
						if(result.indexOf("上一页</a>")>0)
						{
							if(result.indexOf("下一页</a> &#160;")>0)
							{
								String prepagehref=result.substring(result.indexOf("下一页</a> &#160;"),result.indexOf("上一页</a>"));
								prepage=prepagehref.substring(23, prepagehref.length()-2);
								appendpre="<a href=\"ksosearch?sty=3&pno=p&keyword="+kutf8+"\">上一页</a>";
							}
							else
							{
								String prepagehref=result.substring(result.indexOf("<div class=\"d\""),result.indexOf("上一页</a>"));
								prepage=prepagehref.substring(24, prepagehref.length()-2);
								appendpre="<a href=\"ksosearch?sty=3&pno=p&keyword="+kutf8+"\">上一页</a>";
							}
						}	
						result=result.substring(0,result.indexOf("<div class=\"d\">"))+appendnext.trim()+"  "+appendpre.trim();
					}
					request.setAttribute("result", result);
					request.setAttribute("styles", styles);
		    	}		
		}
		else
		{
			request.setAttribute("result", "请输入关键字！<br/><br/>");
		}
		   
		request.setAttribute("now", now);
		return "news";
	}
	
	/**
	 * 图片搜索
	 * @return
	 */
	public String pictureSearch(){
		
		   // f:第一页，n：下一页，p：上一页
		   String pno       = request.getParameter("pno")==null?"f":request.getParameter("pno").toString().trim();    
		   // 搜索关键字
		   String keyword	= request.getParameter("keyword")==null?"":request.getParameter("keyword").toString().trim();
		   
		   String kutf8  = ""; 
		   String result = "";
		   
		   if("f".equals(pno)){
			   
			   String ver	= request.getParameter("ver") ==null?"":request.getParameter("ver").toString().trim();	
			   String src	= request.getParameter("src") ==null?"":request.getParameter("src").toString().trim();	
			   String plat	= request.getParameter("plat")==null?"":request.getParameter("plat").toString().trim();	
			   String imsi	= request.getParameter("imsi")==null?"":request.getParameter("imsi").toString().trim();	
			   String clnt	= request.getParameter("clnt")==null?"":request.getParameter("clnt").toString().trim();	
			   String smsc	= request.getParameter("smsc")==null?"":request.getParameter("smsc").toString().trim();		   
			   pram="ver="+ver+"&amp;src="+src+"&amp;plat="+plat+"&amp;imsi="+imsi+"&amp;clnt="+clnt+"&amp;smsc="+smsc;
			
		   }else{
			   
			   try {
					keyword = new String(keyword.getBytes("ISO8859-1"),"utf-8");
			   } catch (Exception e) {
					e.printStackTrace();
			   }
		   }		  
		   
		   request.setAttribute("pram", pram);		
		   
		   try {
		    	kutf8 = URLEncoder.encode(keyword,"utf-8");
		   } catch (Exception e) {
			    log.info(kutf8+""+e.getMessage());
				e.printStackTrace();
		   }
		    
		   if(keyword.trim().length()>0)
		   {	
				keyword=keyword.replace(" ","");
				request.setAttribute("keyword",keyword);
				
				if("f".equals(pno)){
					String url = "http://m2.baidu.com/img?from=1292a&st=102041&word="+keyword;
					result = RequestUtil.sendConnRequest(url);
				}else if("n".equals(pno)){
					result = RequestUtil.sendConnRequest(nextpage.replace("&amp;","&"));
				}else if("p".equals(pno)){
					result = RequestUtil.sendConnRequest(prepage.replace("&amp;","&"));
				}
				
				
				if(result.indexOf("<div class=\"wm\"> 抱歉")>-1){
					
		    		result="抱歉,没有找到\""+keyword+"\"的相关图片.<br/>";
		    		request.setAttribute("result", result);
		    		
		    	}else{
		    		
		    		String styles = result.substring(result.indexOf("<style"),result.indexOf("</style")+8);
			
					result=result.substring(result.indexOf("<div class=\"mt ct b\">"));
					result=result.replaceAll("<a href=\"./","<a href=\"http://m2.baidu.com/");
					
					String r1 = result.substring(0,result.indexOf("</div>")+6);
					String r2 = result.substring(result.indexOf("<div class=\"wm lh pr\">"),result.indexOf("<form action"));
									
					r1=r1.replaceAll("</a>","</a><br/><br/>");   
					if(r2.endsWith("上一页")){
						r2=r2.replaceAll("上一页",""); 
					}
					if(r2.indexOf("<span>下一页</span>")>0){
						r2=r2.replace("<span>下一页</span>", "");
					}
					 
					String appendnext="",appendpre="";
					if(r2.indexOf("下一页</a>")>0)
					{
						nextpage   = r2.substring(r2.indexOf("<span><a href=\"")+15,r2.indexOf("下一页</a>")-2);		
						appendnext = "<a href=\"ksosearch?sty=2&pno=n&keyword="+kutf8+"\">下一页</a>";
					}	
					
					if(r2.indexOf("上一页</a>")>0)
					{	
						if(r2.indexOf("下一页</a>")>0){
							prepage   = r2.substring(r2.indexOf("</span><a href=\"")+16,r2.indexOf("上一页</a>")-2);
							appendpre = "<a href=\"ksosearch?sty=2&pno=p&keyword="+kutf8+"\">上一页</a>";
						}else{
							prepage = r2.substring(r2.indexOf("<a href=\"")+9,r2.indexOf("上一页</a>")-2);
							appendpre = "<a href=\"ksosearch?sty=2&pno=p&keyword="+kutf8+"\">上一页</a>";
						}
					}	
					result=r1+"<div class=\"wm lh pr\">"+appendnext.trim()+"  "+appendpre.trim()+"</div>";
				
					request.setAttribute("result", result);
					request.setAttribute("styles", styles);
		    	}		
		}
		else
		{
			request.setAttribute("result", "请输入关键字！<br/><br/>");
		}
		   
		request.setAttribute("now", now);
		return "picture";

	}

	/**
	 * 地图搜索
	 * @return
	 */
	public String mapSearch(){
		
		
		return "map";
	}
	
	
	/**
	 * 知道搜索
	 * @return
	 */
	public String knowSearch(){
		
		   // f:第一页，n：下一页，p：上一页
		   String pno       = request.getParameter("pno")==null?"f":request.getParameter("pno").toString().trim();    
		   // 搜索关键字
		   String keyword	= request.getParameter("keyword")==null?"":request.getParameter("keyword").toString().trim();
		   
		   String kutf8  = ""; 
		   String result = "";
		   
		   if("f".equals(pno)){
			   
			   String ver	= request.getParameter("ver")==null?"":request.getParameter("ver").toString().trim();	
			   String src	= request.getParameter("src")==null?"":request.getParameter("src").toString().trim();	
			   String plat	= request.getParameter("plat")==null?"":request.getParameter("plat").toString().trim();	
			   String imsi	= request.getParameter("imsi")==null?"":request.getParameter("imsi").toString().trim();	
			   String clnt	= request.getParameter("clnt")==null?"":request.getParameter("clnt").toString().trim();	
			   String smsc	= request.getParameter("smsc")==null?"":request.getParameter("smsc").toString().trim();		   
			   pram="ver="+ver+"&amp;src="+src+"&amp;plat="+plat+"&amp;imsi="+imsi+"&amp;clnt="+clnt+"&amp;smsc="+smsc;
			
		   }else{
			   try {
					keyword = new String(keyword.getBytes("ISO8859-1"),"utf-8");
			   } catch (Exception e) {
					e.printStackTrace();
			   }
		   }		  
		   
		   request.setAttribute("pram", pram);		
		   
		   try {
		    	kutf8 = URLEncoder.encode(keyword,"utf-8");
		   } catch (Exception e) {
			    log.info(kutf8+""+e.getMessage());
				e.printStackTrace();
		   }
		    
		   if(keyword.trim().length()>0)
		   {	
				keyword=keyword.replace(" ","");
				request.setAttribute("keyword",keyword);
				
				if("f".equals(pno)){
					
					String url = "http://wapiknow.baidu.com/callback?mzl=index&rn=10&u=http%253A%252F%252Fwapiknow.baidu.com%252F%253Fssid%253D0%2526from%253D1292a%2526bd_page_type%253D1%2526uid%253Dwiaui_1343965301_7519%2526pu%253D0%2526st%253D0%2526font%253D0%2526step%253D2&ssid=0&from=1292a" +
				     "&bd_page_type=1&uid=wiaui_1344248234_6207&pu=0&st=0&font=0&step=3&sub0=%E6%90%9C%E7%B4%A2%E7%AD%94%E6%A1%88&word="+keyword;
					
					result = RequestUtil.sendConnRequest(url);
				}else if("n".equals(pno)){
					result = RequestUtil.sendConnRequest(nextpage.replace("&amp;","&"));
				}else if("p".equals(pno)){
					result = RequestUtil.sendConnRequest(prepage.replace("&amp;","&"));
				}
				
				
				if(result.indexOf("相匹配的问题。<br/>")>-1){
					
		    		result="抱歉,没有找到\""+keyword+"\"相匹配的问题.<br/>";
		    		request.setAttribute("result", result);
		    		
		    	}else{
		    		
		    		String styles = result.substring(result.indexOf("<style"),result.indexOf("</style")+8);
					
					result = result.substring(result.indexOf("<div class=\"slist\">"));
					
					result = result.replaceAll("/board?","http://wapiknow.baidu.com/board");
					result = result.replaceAll("index?","http://wapiknow.baidu.com/index");
					result = result.replaceAll("/question/","http://wapiknow.baidu.com/question/");
					
					
					
					String r1 = result.substring(0,result.indexOf("</div>")+6);
					
					String r2 = result.substring(result.lastIndexOf("<div class=\"slist\">")+19,result.indexOf("<div class=\"top\">")-7);
				
					if(r2.endsWith("<span class=\"gray\">上一页</span>")){
						r2=r2.replaceAll("<span class=\"gray\">上一页</span>",""); 
					}
					if(r2.indexOf("<span class=\"gray\">下一页</span>")>0){
						r2=r2.replace("<span class=\"gray\">下一页</span>", "");
					}
					 
					String appendnext="",appendpre="";
					if(r2.indexOf("下一页</a>")>0)
					{
						nextpage   = r2.substring(r2.indexOf("<a class=\"a2\" href=\"")+20,r2.indexOf("下一页</a>")-2);		
						appendnext = "<a href=\"ksosearch?sty=5&pno=n&keyword="+kutf8+"\">下一页</a>";
					}	
					
					if(r2.indexOf("上一页</a>")>0)
					{	
						if(r2.indexOf("下一页</a>")>0){
							prepage   = r2.substring(r2.lastIndexOf("<a class=\"a2\" href=\"")+20,r2.indexOf("上一页</a>")-2);
							appendpre = "<a href=\"ksosearch?sty=5&pno=p&keyword="+kutf8+"\">上一页</a>";
						}else{
							prepage = r2.substring(r2.indexOf("<a class=\"a2\" href=\"")+20,r2.indexOf("上一页</a>")-2);
							appendpre = "<a href=\"ksosearch?sty=5&pno=p&keyword="+kutf8+"\">上一页</a>";
						}
					}	
					result=r1+"<div class=\"slist\">"+appendnext.trim()+"  "+appendpre.trim()+"</div>";
				
					request.setAttribute("result", result);
					request.setAttribute("styles", styles);
		  
		    	}		
		}
		else
		{
			request.setAttribute("result", "请输入关键字！<br/><br/>");
		}
		   
		request.setAttribute("now", now);
		
		return "know";
	}
	/**
	 * 关于酷搜沃
	 * @return
	 */
	@Action(value="aboutkso")
	public String aboutkso(){
		
		request.setAttribute("pram", pram);
		request.setAttribute("now", now);
		return "aboutkso";
	}
	
	/**
	 * 合作
	 * @return
	 */
	@Action(value="coopekso")
	public String coopekso(){
		
		request.setAttribute("pram", pram);
		request.setAttribute("now", now);
		return  "coopekso";
	}
	
}
